package com.cl.cloud.binlog.handler;

import com.cl.cloud.binlog.model.BinlogPositionEntity;
import com.cl.cloud.binlog.properties.DbConfig;
import com.cl.core.redis.cache.RedisJsonOpt;
import com.cl.core.common.contants.ResultCode;
import com.cl.core.common.exception.ServerException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @description: redis位点处理器
 * @author: liuzijian
 * @time: 2022-07-08 11:46
 */
@Slf4j
public class RedisPositionHandler implements PositionHandler {

    private final String position_redis_key_prefix = "binlog-position:";

    private final String binlog_distributed_lock_key_prefix = "binlog-distributed-lock:";

    private final RedisJsonOpt redisJsonOpt;

    public RedisPositionHandler(RedisJsonOpt redisJsonOpt) {
        this.redisJsonOpt = redisJsonOpt;
    }

    @Override
    public BinlogPositionEntity getPosition(DbConfig dbConfig) throws ServerException {
        try {
            String key = position_redis_key_prefix + dbConfig.getHost() + ":" + dbConfig.getPort();
            String position = redisJsonOpt.get(key);//以数据库地址+端口组合作为key
            if (position != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.readValue(position, BinlogPositionEntity.class);
            }
        } catch (JsonProcessingException e) {
            log.error("获取位点异常", e);
            return null;
        }
        return null;
    }

    @Override
    public void savePosition(DbConfig dbConfig, BinlogPositionEntity binlogPositionEntity) throws ServerException {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String key = position_redis_key_prefix + dbConfig.getHost() + ":" + dbConfig.getPort();
            redisJsonOpt.set(key, objectMapper.writeValueAsString(binlogPositionEntity));
        } catch (JsonProcessingException e) {
            throw new ServerException(ResultCode.SERVER_ERROR, e);
        }
    }
}
